var connect = require('connect');
var url = require('url');

var app = connect();

var routes = {
  GET: {
    '/users': function(req,res){
      res.end('/users/.....GET');
    },
    '/user/:id': function(req,res,id){
      res.end('/users/'+ id + '........GET');
    }
  },
  POST: {
    '/upload' : function(req,res){
      res.end('/upload.......POST');
    }
  }
};

app.use(logger(':url  :method'));
app.use(router(routes));

app.listen(3000);
console.log('Server is start @3000');

function logger(str){
  var ex = /:(\w+)/g;
  return function(req,res,next){
    var result = str.replace(ex,function(match,property){
      return req[property];
    });
    console.log(result);
    next();
  }  
}

function router(obj){
  return function(req,res,next){
    var routes = obj[req.method];
    var reqUrl = url.parse(req.url); 
    var paths = Object.keys(routes);
    for (var i=0 ; i<paths.length; i++){
      var path = paths[i];
      var fn = routes[path];
      var path = path.replace(/\//g, '\/').replace(/:(\w+)/g,'([^\\/:]+)');
      var re = new RegExp('^'+ path +'$');
      console.log(reqUrl.pathname);
      var captures = reqUrl.pathname.match(re);
      console.log(captures);
      if (captures){
        var args = [req,res].concat(captures.slice(1));
        fn.apply(null, args);
        return;
      }
    }
    next();
  }
}
